package com.zh.webcommon;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import org.apache.commons.lang3.SystemUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Zhou
 * @date 14:36 2025/7/4
 */
public final class CommonConst {

    /* 机器节点名称 */
    public static String NODE_HOST_NAME = String.format("%s (%s)", SystemUtils.getHostName(), SystemUtils.OS_NAME).intern();
    /* 节点的通用应用账号+ROLE */
    public static final String NODE_IDENTITY = "server_guest";
    public static final String NODE_ROLE = "SERVER_NODE";

    /* 时间相关 单位为秒 */
    public static final int MINUTE = 60;
    public static final int HOUR = 3600;
    public static final int DAY = 24 * 3600;

    public static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

    public static final Gson GSON;

    static {
        //序列化
        final JsonSerializer<LocalDateTime> jsonSerializerDateTime = (localDateTime, type, jsonSerializationContext)
                -> new JsonPrimitive(localDateTime.format(DATE_TIME_FORMAT));
        final JsonSerializer<LocalDate> jsonSerializerDate = (localDate, type, jsonSerializationContext)
                -> new JsonPrimitive(localDate.format(DATE_TIME_FORMAT));
        //反序列化
        final JsonDeserializer<LocalDateTime> jsonDeserializerDateTime = (jsonElement, type, jsonDeserializationContext)
                -> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DATE_TIME_FORMAT);
        final JsonDeserializer<LocalDate> jsonDeserializerDate = (jsonElement, type, jsonDeserializationContext)
                -> LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(), DATE_TIME_FORMAT);

        GSON = new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, jsonSerializerDateTime)
                .registerTypeAdapter(LocalDate.class, jsonSerializerDate)
                .registerTypeAdapter(LocalDateTime.class, jsonDeserializerDateTime)
                .registerTypeAdapter(LocalDate.class, jsonDeserializerDate)
                .create();
    }


}
